package com.hondee.fuzzyquery.query;

import org.springframework.jdbc.core.JdbcTemplate;

import com.hondee.fuzzyquery.entity.access.CachedAccess;
import com.hondee.fuzzyquery.entity.access.DBQuery;
import com.hondee.fuzzyquery.entity.access.IEntityAccess;
import com.hondee.fuzzyquery.entity.access.IQueryCondition;
import com.hondee.fuzzyquery.entity.access.OrderType;
import com.hondee.fuzzyquery.entity.access.QueryOrder;
import com.hondee.fuzzyquery.entity.access.SqlServerTableAccess;
import com.hondee.fuzzyquery.entity.access.querycondition.FuzzyConditionGenerator;

public class EntityAccessFactory {
	
	private static final String QUERY_SPLITER = "\\s+|,|，";
	
	public static IEntityAccess getAccess(IQueryTarget target
			,Integer pageIndex
			,Integer pageSize
			,String queryStringInput
			,JdbcTemplate jdbcTemplate){
		if(target instanceof DBTableQueryTarget){
			return getDBTableAccess((DBTableQueryTarget)target,pageIndex,pageSize,queryStringInput,jdbcTemplate);
		}
		return null;
		
	}
	
	public static IEntityAccess getDBTableAccess(DBTableQueryTarget target
			,Integer pageIndex
			,Integer pageSize
			,String queryStringInput
			,JdbcTemplate jdbcTemplate){
		
		String[] queryStringArray = queryStringInput.split(QUERY_SPLITER);
		
		IQueryCondition condition = FuzzyConditionGenerator.generate(target.getFuzzyFields(), queryStringArray);
		
		if(condition==null){
			throw new RuntimeException("query condition is null.");
		}
		
		String[] queryOrder = target.getQueryOrder();
		QueryOrder[] queryOrderList = new QueryOrder[queryOrder.length];
		
		for(int i=0;i<queryOrder.length;i++){
			String[] split = queryOrder[i].split("\\s+");
			if(split.length!=2){
				continue;
			}
			queryOrderList[i] = new QueryOrder(split[0].trim(), OrderType.get(split[1].trim()));
		}
		
		DBQuery query = new DBQuery(target.getName()
				, target.isPaging()
				, pageIndex
				, pageSize
				, target.getQueryFields()
				, condition
				, queryOrderList);
		SqlServerTableAccess sqlServerTableAccess = new SqlServerTableAccess(target.getIdentity(),query, jdbcTemplate);
		if(target.isCache()){
			return new CachedAccess(sqlServerTableAccess);
		}else{
			return sqlServerTableAccess;
		}
	}
	
}
